package cn.xiaopengstack.domain.agent.service.execute.auto.node;

import cn.bugstack.wrench.design.framework.tree.StrategyHandler;
import cn.xiaopengstack.domain.agent.model.entity.AutoAgentExecuteResultEntity;
import cn.xiaopengstack.domain.agent.model.entity.ExecuteCommandEntity;
import cn.xiaopengstack.domain.agent.model.valobj.AiAgentClientFlowConfigVO;
import cn.xiaopengstack.domain.agent.model.valobj.AiClientTypyEnumVO;
import cn.xiaopengstack.domain.agent.service.execute.auto.AbstractExecuteSupport;
import cn.xiaopengstack.domain.agent.service.execute.auto.factory.DefaultAutoAgentExecuteStrategyFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Component;

/**
 * @author jiangyangang
 */
@Component("step1AnalyzerNode")
@Slf4j
public class Step1AnalyzerNode extends AbstractExecuteSupport {

    @Override
    protected String doApply(ExecuteCommandEntity requestParameter, DefaultAutoAgentExecuteStrategyFactory.DynamicContext dynamicContext) throws Exception {

        // 获取ChatClient
        AiAgentClientFlowConfigVO clientConfigVO = dynamicContext.getAiAgentClientFlowConfigVOMap().get(AiClientTypyEnumVO.TASK_ANALYZER_CLIENT.getCode());

        // 组装ChatClient
        ChatClient chatClient = getClientByClientId(clientConfigVO.getClientId());

        log.info("\n📊 阶段1: 任务状态分析");
        String analysisPrompt = String.format(clientConfigVO.getStepPrompt(),
                requestParameter.getMessage(),
                dynamicContext.getStep(),
                dynamicContext.getMaxSteps(),
                dynamicContext.getExecutionHistory().isEmpty() ? "[首次执行]" : dynamicContext.getExecutionHistory().toString(),
                dynamicContext.getCurrentTask());

        // 执行结果过
        String analysisResult = chatClient.prompt(analysisPrompt)
                .advisors(a -> a
                        .param(CHAT_MEMORY_CONVERSATION_ID_KEY, requestParameter.getSessionId())
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 1024))
                .call().content();
        assert analysisResult != null;

        // 处理AI对话结果
        parseAnalysisResult(dynamicContext, analysisResult, requestParameter.getSessionId());
        dynamicContext.setValue(DefaultAutoAgentExecuteStrategyFactory.DynamicContext.Key.analysisResult, analysisResult);


        // 执行下一个节点
        return router(requestParameter, dynamicContext);
    }

    @Override
    public StrategyHandler<ExecuteCommandEntity, DefaultAutoAgentExecuteStrategyFactory.DynamicContext, String> get(ExecuteCommandEntity requestParameter, DefaultAutoAgentExecuteStrategyFactory.DynamicContext dynamicContext) throws Exception {
        if (isCompleted(dynamicContext)) {
            return getBean("step4LogExecutionSummaryNode");
        }

        return getBean("step2PrecisionExecutorNode");
    }

    /**
     * 解析任务分析结果
     */
    private void parseAnalysisResult(DefaultAutoAgentExecuteStrategyFactory.DynamicContext dynamicContext, String analysisResult, String sessionId) {
        int step = dynamicContext.getStep();
        log.info("\n📊 === 第 {} 步分析结果 ===", step);

        String[] lines = analysisResult.split("\n");
        String currentSection = "";
        StringBuilder sectionContent = new StringBuilder();

        for (String line : lines) {
            line = line.trim();
            if (line.isEmpty()) continue;

            if (line.contains("任务状态分析:")) {
                sendAnalysisSubResult(dynamicContext, currentSection, sectionContent.toString(), sessionId);
                currentSection = "analysis_status";
                sectionContent = new StringBuilder();
                log.info("\n🎯 任务状态分析:");
                continue;
            } else if (line.contains("执行历史评估:")) {
                sendAnalysisSubResult(dynamicContext, currentSection, sectionContent.toString(), sessionId);

                currentSection = "analysis_history";
                sectionContent = new StringBuilder();

                log.info("\n📈 执行历史评估:");
                continue;
            } else if (line.contains("下一步策略:")) {
                sendAnalysisSubResult(dynamicContext, currentSection, sectionContent.toString(), sessionId);
                currentSection = "analysis_strategy";
                sectionContent = new StringBuilder();
                log.info("\n🚀 下一步策略:");
                continue;
            } else if (line.contains("完成度评估:")) {
                sendAnalysisSubResult(dynamicContext, currentSection, sectionContent.toString(), sessionId);
                sectionContent = new StringBuilder();
                currentSection = "analysis_progress";
                String progress = line.substring(line.indexOf(":") + 1).trim();
                log.info("\n📊 完成度评估: {}", progress);
                continue;
            } else if (line.contains("任务状态:")) {
                sendAnalysisSubResult(dynamicContext, currentSection, sectionContent.toString(), sessionId);
                sectionContent = new StringBuilder();
                currentSection = "analysis_task_status";
                String status = line.substring(line.indexOf(":") + 1).trim();
                if (status.equals("COMPLETED")) {
                    log.info("\n✅ 任务状态: 已完成");
                } else {
                    log.info("\n🔄 任务状态: 继续执行");
                }
                sectionContent.append(line).append("\n");
                continue;
            }
            // 收集当前section的内容
            switch (currentSection) {
                case "analysis_status":
                    log.info("   📋 {}", line);
                    break;
                case "analysis_history":
                    log.info("   📊 {}", line);
                    break;
                case "analysis_strategy":
                    log.info("   🎯 {}", line);
                    break;
                default:
                    log.info("   📝 {}", line);
                    break;
            }
        }
        sendAnalysisSubResult(dynamicContext, currentSection, sectionContent.toString(), sessionId);
    }

    /**
     * 发送分析阶段细分结果到流式输出
     */
    private void sendAnalysisSubResult(DefaultAutoAgentExecuteStrategyFactory.DynamicContext dynamicContext,
                                       String subType, String content, String sessionId) {
        if (!subType.isEmpty() && !content.isEmpty()) {
            AutoAgentExecuteResultEntity result = AutoAgentExecuteResultEntity.createAnalysisSubResult(
                    dynamicContext.getStep(), subType, content, sessionId);
            sendSseResult(dynamicContext, result);
        }
    }

}
